package com.hjh.testdemo.framework.audio

import android.content.Context
import android.media.MediaPlayer
import android.net.Uri
import java.io.IOException

/**
 * @author： hjh
 * @createDate： 2025/6/5 15:22
 * @description： 音频播放器
 * @qq： 3472903821
 * @version: 1.0
 */
@Suppress("unused")
class AudioPlayer(private val context: Context) {

    private var mediaPlayer: MediaPlayer? = null
    private var currentAudioUri: Uri? = null
    private var isPrepared = false

    fun loadAudio(uri: Uri, onPrepared: () -> Unit = {}, onError: (String) -> Unit = {}) {
        release()
        currentAudioUri = uri

        try {
            mediaPlayer = MediaPlayer().apply {
                setDataSource(context, uri)
                setOnPreparedListener {
                    isPrepared = true
                    onPrepared()
                }
                setOnErrorListener { _, what, extra ->
                    onError("播放错误: what=$what, extra=$extra")
                    false
                }
                prepareAsync() // 异步准备
            }
        } catch (e: IOException) {
            onError("加载音频失败: ${e.message}")
        } catch (e: IllegalArgumentException) {
            onError("无效的音频源: ${e.message}")
        }
    }

    fun play(onStart: () -> Unit = {}, onError: (String) -> Unit = {}) {
        if (mediaPlayer == null || !isPrepared) {
            onError("音频未准备好")
            return
        }

        try {
            if (!mediaPlayer!!.isPlaying) {
                mediaPlayer!!.start()
                onStart()
            }
        } catch (e: IllegalStateException) {
            onError("播放失败: ${e.message}")
        }
    }

    fun pause() {
        mediaPlayer?.takeIf { it.isPlaying }?.pause()
    }

    fun stop() {
        mediaPlayer?.stop()
        isPrepared = false
    }

    fun isPlaying(): Boolean = mediaPlayer?.isPlaying ?: false

    fun release() {
        mediaPlayer?.release()
        mediaPlayer = null
        isPrepared = false
        currentAudioUri = null
    }

    fun getCurrentPosition(): Int = mediaPlayer?.currentPosition ?: 0

    fun getDuration(): Int = mediaPlayer?.duration ?: 0

    fun seekTo(position: Int) {
        mediaPlayer?.seekTo(position)
    }
}